package com.czy.owner.ui.garage;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czy.otherlib.wheelview.adapters.ArrayWheelAdapter;
import com.czy.otherlib.wheelview.widget.OnWheelScrollListener;
import com.czy.otherlib.wheelview.widget.WheelView;
import com.czy.owner.R;
import com.czy.owner.adapter.CarColorAdapter;
import com.czy.owner.entity.CarBrandModel;
import com.czy.owner.entity.CarInfo;
import com.czy.owner.global.Constants;
import com.czy.owner.db.UserHelper;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.illegalquery.IllegalQueryActivity;
import com.czy.owner.utils.*;
import com.czy.owner.widget.PageTitleView;
import com.czy.owner.widget.RoundImageView;
import com.easyrecycleview.EasyRecyclerView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.lang.reflect.Array;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import butterknife.BindView;

/**
 * Created by King on 2016/6/14 0014.
 */
public class EditCarActivity extends BaseActivity {
    private final String TAG = getClass().getSimpleName();
    @BindView(R.id.iv_brand_logo)
    RoundImageView ivBrandLogo;
    @BindView(R.id.tv_car_brand)
    TextView tvCarBrand;
    @BindView(R.id.tv_car_line)
    TextView tvCarLine;
    @BindView(R.id.tv_reset_car_brand)
    TextView tvResetCarBrand;
    @BindView(R.id.ll_car_code_select)
    LinearLayout llCarCodeSelect;
    @BindView(R.id.tv_province_code)
    TextView tvProvinceCode;
    @BindView(R.id.tv_provinve_char)
    TextView tvProvinceChar;
    @BindView(R.id.et_license_plate)
    EditText etLicensePlate;
    @BindView(R.id.tv_license_year)
    TextView tvLicenseYear;
    @BindView(R.id.tv_purchase_date)
    TextView tvPurchaseDate;
    @BindView(R.id.ll_car_color_select)
    LinearLayout llCarColor;
    @BindView(R.id.tv_car_color)
    TextView tvCarColor;
    @BindView(R.id.et_total_mileage)
    EditText etTotalMileage;
    @BindView(R.id.et_vehicle_identify_number)
    EditText etVIN;
    @BindView(R.id.et_engine_number)
    EditText etEngineNumber;
    @BindView(R.id.iv_vehicle_tips1)
    ImageView ivGuideTips1;
    @BindView(R.id.iv_vehicle_tips2)
    ImageView ivGuideTips2;
    Dialog guideDialog;
    @BindView(R.id.btn_edit_car_submit)
    Button btnSubmit;
    PageTitleView pageTitle;
    @BindView(R.id.rv_province_code)
    EasyRecyclerView rvProvinceCode;
    public enum ACTION_TYPE {
        ADD,
        MODIFY
    }

    public static final String ACTION_TYPE_KEY = "action_type";
    private ACTION_TYPE actionType;
    private CarInfo mCarInfo = new CarInfo();
    private CarBrandModel mCarBrandModel = new CarBrandModel();

    private int currentYear, currentMonth, currentDay;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_edit_car;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        if (getIntent().getExtras() == null) {
            PhoneUtils.ShowToastMessage(this, "数据异常");
            finish();
            return;
        }
        actionType = (ACTION_TYPE) getIntent().getExtras().getSerializable(ACTION_TYPE_KEY);
        if (actionType == null || actionType != ACTION_TYPE.MODIFY) {
            actionType = ACTION_TYPE.ADD;
            mCarBrandModel = (CarBrandModel) getIntent().getExtras().getSerializable(Constants.TRANSMISSION_CONTENT_KEY);
        } else {
            mCarInfo = (CarInfo) getIntent().getExtras().getSerializable(Constants.TRANSMISSION_CONTENT_KEY);
        }
        pageTitle = new PageTitleView((RelativeLayout) findViewById(R.id.rl_page_title), getResources().getString(R.string.garage_edit_car), true);
        Calendar c = Calendar.getInstance();
        currentYear = c.get(Calendar.YEAR);
        currentMonth = c.get(Calendar.MONTH) + 1;
        currentDay = c.get(Calendar.DAY_OF_MONTH);
        CarUtils.shortHands(EditCarActivity.this);
        CarUtils.ShowNumber(EditCarActivity.this, rvProvinceCode, etLicensePlate);
        CarUtils.etChangeListener(etLicensePlate,rvProvinceCode);
        initListener();
        initData();
        SoftKeyBoardListener.setListener(EditCarActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {

            }

            @Override
            public void keyBoardHide(int height) {
                rvProvinceCode.setVisibility(View.GONE);
                etLicensePlate.clearFocus();

            }
        });
    }

    @Override
    protected void updateViews() {

    }


    private void initListener() {
        pageTitle.getLeftButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvResetCarBrand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(EditCarActivity.this, PickBrandActivity.class);
                // 修改车辆无需返回
                intent.putExtra(PickBrandActivity.START_FLAG, 1);
                startActivityForResult(intent, 0);
            }
        });
        llCarCodeSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strProvinceCode = tvProvinceCode.getText().toString().trim();
                String strProvinceShortChar = tvProvinceChar.getText().toString().trim();
                CarUtils.showProvinceDialog(EditCarActivity.this,tvProvinceCode,strProvinceCode,tvProvinceChar,strProvinceShortChar);
            }
        });

        tvLicenseYear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showYearDialog();
            }
        });
        tvPurchaseDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDateDialog();
            }
        });
        llCarColor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showColorDialog();
            }
        });
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String provinceChar = tvProvinceChar.getText().toString().trim();
                String licensePlate = etLicensePlate.getText().toString().trim();
                StringBuilder codeSb = new StringBuilder();
                codeSb.append(provinceChar+licensePlate);
//                if (!PhoneUtils.checkLicensePlate(codeSb.toString())) {
//                    PhoneUtils.ShowToastMessage(EditCarActivity.this, "车牌号码不合法!");
//                    etLicensePlate.requestFocus();
//                    return;
//                }

                if (TextUtils.isEmpty(licensePlate)) {
                    PhoneUtils.ShowToastMessage(EditCarActivity.this, "车牌号码不能为空");
                    return;
                }


                if(licensePlate.length()<5){
                    PhoneUtils.ShowToastMessage(EditCarActivity.this, "车牌号码不合法");
                    return;
                }




                RequestParams params;
                if (actionType == ACTION_TYPE.ADD) {
                    params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_CAR_ADD);
                } else {
                    params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_CAR_UPDATE);
                }


                if (!TextUtils.isEmpty(etTotalMileage.getText().toString().trim())) {
                    params.addBodyParameter("currentMileage", etTotalMileage.getText().toString().trim());
                }else {
                    params.addBodyParameter("currentMileage", "0");
                }

                btnSubmit.setEnabled(false);
                mLoadView.ShowLoadView("正在提交数据");
                params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(EditCarActivity.this).getSession());
                params.addBodyParameter("licenseNumber", tvProvinceCode.getText().toString()+codeSb.toString());
                if (!TextUtils.isEmpty(tvLicenseYear.getText().toString().trim())) {
                    Calendar mCalendar = Calendar.getInstance();
                    mCalendar.set(Integer.parseInt(tvLicenseYear.getText().toString().trim()),1,1);
                    params.addBodyParameter("licenseAddTime", "" + mCalendar.getTimeInMillis());
                } else {
                    params.addBodyParameter("licenseAddTime", "");
                }
                if (!TextUtils.isEmpty(tvPurchaseDate.getText().toString().trim())) {
                    DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                    Date date = null;
                    try {
                        date  = format1.parse(tvPurchaseDate.getText().toString().trim());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if(date==null){
                        params.addBodyParameter("buyTime", "");
                    }else{
                        params.addBodyParameter("buyTime", "" + date.getTime());
                    }
                } else {
                    params.addBodyParameter("buyTime", "");
                }

                if (!TextUtils.isEmpty(etVIN.getText().toString().trim())) {
                    if(!PhoneUtils.checkVINisLegal(etVIN.getText().toString().trim())){
                        PhoneUtils.ShowToastMessage(EditCarActivity.this, "请正确输入车架号!");
                        etVIN.requestFocus();
                        mLoadView.CancleLoadView();
                        btnSubmit.setEnabled(true);
                        return;
                    }
                    params.addBodyParameter("chassisNumber", etVIN.getText().toString().trim());
                } else {
                    params.addBodyParameter("chassisNumber", "");
                }
                if (!TextUtils.isEmpty(etEngineNumber.getText().toString().trim())) {
                    params.addBodyParameter("engineType", etEngineNumber.getText().toString().trim());
                } else {
                    params.addBodyParameter("engineType", "");
                }
                if (!TextUtils.isEmpty(tvCarColor.getText().toString().trim())) {
                    params.addBodyParameter("color", tvCarColor.getText().toString().trim());
                } else {
                    params.addBodyParameter("color", "");
                }
                if (actionType == ACTION_TYPE.ADD) {
                    params.addBodyParameter("carBrandId", "" + mCarBrandModel.getCarBrandId());
                    MyLog.e("RAVEN","添加车："+params);
                    x.http().post(params, new Callback.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String result) {
                            String data = PhoneUtils.checkResponseFlag(EditCarActivity.this, result);
                            if (data != null) {
                                PhoneUtils.ShowToastMessage(EditCarActivity.this, "车辆添加成功");
                                setResult(Constants.ACTIVITY_RESULT_CODE_CAR_ADD);
                                finish();
                            }
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            PhoneUtils.ShowToastMessage(EditCarActivity.this, "数据提交异常,请重试");
                        }

                        @Override
                        public void onCancelled(CancelledException cex) {

                        }

                        @Override
                        public void onFinished() {
                            mLoadView.CancleLoadView();
                            btnSubmit.setEnabled(true);
                            mLoadView.CancleLoadView();
                        }
                    });
                } else {
                    params.addBodyParameter("carBrandId", "" + mCarInfo.getCarBrandId());
                    params.addBodyParameter("ownerCarId", "" + mCarInfo.getOwnerCarId());
                    MyLog.e("RAVEN","编辑车："+params);
                    x.http().post(params, new Callback.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String result) {
                            String data = PhoneUtils.checkResponseFlag(EditCarActivity.this, result);
                            if (data != null) {
                                PhoneUtils.ShowToastMessage(EditCarActivity.this, "车辆修改成功");
                                setResult(Constants.ACTIVITY_RESULT_CODE_CAR_ADD);
                                // TODO 可以考虑修改缓存数据
                                finish();
                            }
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            PhoneUtils.ShowToastMessage(EditCarActivity.this, "数据提交异常,请重试");
                        }

                        @Override
                        public void onCancelled(CancelledException cex) {

                        }

                        @Override
                        public void onFinished() {
                            mLoadView.CancleLoadView();
                            btnSubmit.setEnabled(true);
                            mLoadView.CancleLoadView();
                        }
                    });
                }
            }
        });

        ivGuideTips1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showVehicleTips();
            }
        });
        ivGuideTips2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showVehicleTips();
            }
        });
    }

    private void initData() {
        if (actionType == ACTION_TYPE.ADD) {
            x.image().bind(ivBrandLogo, mCarBrandModel.getImageSrc(), new Callback.CommonCallback<Drawable>() {
                @Override
                public void onSuccess(Drawable result) {
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ivBrandLogo.setImageResource(R.mipmap.default_icon);
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
            tvCarBrand.setText(mCarBrandModel.getChName());
        } else {
            x.image().bind(ivBrandLogo, mCarInfo.getImageSrc(), new Callback.CommonCallback<Drawable>() {
                @Override
                public void onSuccess(Drawable result) {
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ivBrandLogo.setImageResource(R.mipmap.default_icon);
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

            tvCarBrand.setText(mCarInfo.getChName());
            if (mCarInfo.getLicenseNumber().length() >= 6) {
                String provinceShortName = mCarInfo.getLicenseNumber().substring(0, 1);
                String provinceShortChar = mCarInfo.getLicenseNumber().substring(1, 2);
                tvProvinceCode.setText(provinceShortName);
                tvProvinceChar.setText(provinceShortChar);
                String carCodeNumber = mCarInfo.getLicenseNumber().substring(2, mCarInfo.getLicenseNumber().length());
                etLicensePlate.setText(carCodeNumber);
            }

            if (mCarInfo.getLicenseAddTime() == 0) {
                tvLicenseYear.setText("");
            } else {
                Calendar c = Calendar.getInstance();
                c.setTimeInMillis(mCarInfo.getLicenseAddTime());
                tvLicenseYear.setText("" + c.get(Calendar.YEAR));
            }
            if (mCarInfo.getBuyTime() == 0) {
                tvPurchaseDate.setText("");
            } else {
                Date date = new Date(mCarInfo.getBuyTime());
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                tvPurchaseDate.setText("" + format.format(date));
            }
            if(TextUtils.isEmpty(mCarInfo.getColor())){
                tvCarColor.setText("");
            }else{
                tvCarColor.setText(mCarInfo.getColor());
            }
            if(mCarInfo.getCurrentMileage()>0) {
                etTotalMileage.setText("" + mCarInfo.getCurrentMileage());
            }
            if ("未设置车架号".equals(mCarInfo.getChassisNumber())) {
                etVIN.setText("");
            } else {
                etVIN.setText(mCarInfo.getChassisNumber());
            }
            etEngineNumber.setText(mCarInfo.getEngineType());
        }
    }







    private void showYearDialog() {
        int yearIndex = 0;

        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display mDisplay = windowManager.getDefaultDisplay();
        final Dialog mDateDialog = new Dialog(EditCarActivity.this, R.style.AlertDialogStyle);
        View dialogView = LayoutInflater.from(EditCarActivity.this).inflate(R.layout.dialog_archive_add_date, null);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure);
        TextView tvTitle = (TextView) dialogView.findViewById(R.id.tv_archive_add_title);
        tvTitle.setText("请选择年份");
        final WheelView wvYear = (WheelView) dialogView.findViewById(R.id.wv_archive_date_year);
        final WheelView wvMonth = (WheelView) dialogView.findViewById(R.id.wv_archive_date_month);
        final WheelView wvDay = (WheelView) dialogView.findViewById(R.id.wv_archive_date_day);
        wvMonth.setVisibility(View.GONE);
        wvDay.setVisibility(View.GONE);


        final String[] yearArray = new String[20];
        for (int i = currentYear; i > currentYear - 20; i--) {
            yearArray[currentYear - i] = "" + i + "年";
            if (!TextUtils.isEmpty(tvLicenseYear.getText()) && i == Integer.valueOf(tvLicenseYear.getText().toString())) {
                yearIndex = currentYear - i;
            }
        }
        ArrayWheelAdapter<String> yearAdapter = new ArrayWheelAdapter<String>(this, yearArray);
        yearAdapter.setTextSize(20);
        wvYear.setViewAdapter(yearAdapter);
        wvYear.setCurrentItem(yearIndex);

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDateDialog.dismiss();
            }
        });
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txtYear = yearArray[wvYear.getCurrentItem()].replace("年", "");
                tvLicenseYear.setText(txtYear);
                mDateDialog.dismiss();
            }
        });

        mDateDialog.setContentView(dialogView);
        mDateDialog.setCancelable(true);
        mDateDialog.setCanceledOnTouchOutside(true);

        Window dialogWindow = mDateDialog.getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (mDisplay.getWidth() * 0.86);
        dialogWindow.setAttributes(p);
        mDateDialog.show();
    }

    private void showDateDialog() {
        int yearIndex = 0, monthIndex = currentMonth - 1, dayIndex = currentDay - 1;
        Calendar tmpCalendar = Calendar.getInstance();
        Date date = null;
        if (!TextUtils.isEmpty(tvPurchaseDate.getText())) {
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = formatter.parse(tvPurchaseDate.getText().toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(date !=null){
                tmpCalendar.setTime(date);
            }
        }
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display mDisplay = windowManager.getDefaultDisplay();
        final Dialog mDateDialog = new Dialog(EditCarActivity.this, R.style.AlertDialogStyle);
        View dialogView = LayoutInflater.from(EditCarActivity.this).inflate(R.layout.dialog_archive_add_date, null);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure);
        TextView tvTitle = (TextView) dialogView.findViewById(R.id.tv_archive_add_title);
        tvTitle.setText("请选择时间");
        final WheelView wvYear = (WheelView) dialogView.findViewById(R.id.wv_archive_date_year);
        final WheelView wvMonth = (WheelView) dialogView.findViewById(R.id.wv_archive_date_month);
        final WheelView wvDay = (WheelView) dialogView.findViewById(R.id.wv_archive_date_day);


        final String[] yearArray = new String[20];
        for (int i = currentYear; i > currentYear - 20; i--) {
            yearArray[currentYear - i] = "" + i + "年";
            if (date != null && tmpCalendar.get(Calendar.YEAR) == i) {
                yearIndex = currentYear - i;
            }
        }
        ArrayWheelAdapter<String> yearAdapter = new ArrayWheelAdapter<String>(this, yearArray);
        yearAdapter.setTextSize(20);
        wvYear.setViewAdapter(yearAdapter);
        wvYear.setCurrentItem(yearIndex);
        wvYear.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex = wvDay.getCurrentItem();
                int tmpDayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[wvYear.getCurrentItem()].replace("年", "")), wvMonth.getCurrentItem() + 1);
                String[] tmpDayArray = new String[tmpDayOfMonth];
                for (int k = 0; k < tmpDayOfMonth; k++) {
                    tmpDayArray[k] = "" + (k + 1) + "日";
                }
                if (tmpIndex >= tmpDayOfMonth) {
                    tmpIndex = tmpDayOfMonth - 1;
                }
                ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(EditCarActivity.this, tmpDayArray);
                dayAdapter.setTextSize(20);
                wvDay.setViewAdapter(dayAdapter);
                wvDay.setCurrentItem(tmpIndex);
            }
        });

        final String[] monthArray = new String[12];
        for (int j = 0; j < 12; j++) {
            monthArray[j] = "" + (j + 1) + "月";
            if (date != null && tmpCalendar.get(Calendar.MONTH) == j) {
                monthIndex = j;
            }
        }
        ArrayWheelAdapter<String> monthAdapter = new ArrayWheelAdapter<String>(this, monthArray);
        monthAdapter.setTextSize(20);
        wvMonth.setViewAdapter(monthAdapter);
        wvMonth.setCurrentItem(monthIndex);
        wvMonth.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex = wvDay.getCurrentItem();
                int tmpDayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[wvYear.getCurrentItem()].replace("年", "")), wvMonth.getCurrentItem() + 1);
                String[] tmpDayArray = new String[tmpDayOfMonth];
                for (int k = 0; k < tmpDayOfMonth; k++) {
                    tmpDayArray[k] = "" + (k + 1) + "日";
                }
                if (tmpIndex >= tmpDayOfMonth) {
                    tmpIndex = tmpDayOfMonth - 1;
                }
                ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(EditCarActivity.this, tmpDayArray);
                dayAdapter.setTextSize(20);
                wvDay.setViewAdapter(dayAdapter);
                wvDay.setCurrentItem(tmpIndex);
            }
        });

        int dayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[yearIndex].replace("年", "")), monthIndex + 1);
        final String[] dayArray = new String[dayOfMonth];
        for (int k = 0; k < dayOfMonth; k++) {
            dayArray[k] = "" + (k + 1) + "日";
            if (date != null && tmpCalendar.get(Calendar.DATE) == k + 1) {
                dayIndex = k;
            }
        }
        ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(this, dayArray);
        dayAdapter.setTextSize(20);
        wvDay.setViewAdapter(dayAdapter);
        wvDay.setCurrentItem(dayIndex);

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDateDialog.dismiss();
            }
        });
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txtYear = yearArray[wvYear.getCurrentItem()].replace("年", ""),
                        txtMonth = "0" + (wvMonth.getCurrentItem() + 1),
                        txtDay = "0" + (wvDay.getCurrentItem() + 1);
                txtMonth = txtMonth.substring(txtMonth.length() - 2);
                txtDay = txtDay.substring(txtDay.length() - 2);
                //tvPurchaseDate.setText(txtYear + "-" + txtMonth + "-" + txtDay);

                Calendar now = Calendar.getInstance();
                int year = now.get(Calendar.YEAR);
                int month = (now.get(Calendar.MONTH) + 1);
                int day = now.get(Calendar.DAY_OF_MONTH);
                if (year == Integer.valueOf(txtYear)) {
                    if (month < Integer.valueOf(txtMonth)) {
                        PhoneUtils.ShowToastMessage(EditCarActivity.this, "不得超过当前日期");
                    } else if (month == Integer.valueOf(txtMonth) && day < Integer.valueOf(txtDay)) {
                        PhoneUtils.ShowToastMessage(EditCarActivity.this, "不得超过当前日期");
                    } else {
                        tvPurchaseDate.setText(txtYear + "-" + txtMonth + "-" + txtDay);
                        mDateDialog.dismiss();
                    }
                }
                else {
                    tvPurchaseDate.setText(txtYear + "-" + txtMonth + "-" + txtDay);
                    mDateDialog.dismiss();
                }

            }
        });

        mDateDialog.setContentView(dialogView);
        mDateDialog.setCancelable(true);
        mDateDialog.setCanceledOnTouchOutside(true);

        Window dialogWindow = mDateDialog.getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (mDisplay.getWidth() * 0.86);
        dialogWindow.setAttributes(p);
        mDateDialog.show();
    }
    private void showColorDialog() {
        int yearIndex = 0;

        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display mDisplay = windowManager.getDefaultDisplay();
        final Dialog mColorDialog = new Dialog(EditCarActivity.this, R.style.AlertDialogStyle);
        View dialogView = LayoutInflater.from(EditCarActivity.this).inflate(R.layout.dialog_archive_add_car_color, null);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure);
        TextView tvTitle = (TextView) dialogView.findViewById(R.id.tv_archive_add_title);
        tvTitle.setText("请选择车身颜色");
        RecyclerView rvCarColor = (RecyclerView) dialogView.findViewById(R.id.rv_car_color);
        List<String> colorList = Arrays.asList("红色","白色", "珍珠白","黑色","蓝色","灰色","土豪金","黄色","紫色","绿色","棕色","银色","其他");

        final CarColorAdapter colorAdapter = new CarColorAdapter(this, colorList ,tvCarColor.getText().toString());
        GridLayoutManager layoutManager = new GridLayoutManager(this, 4);
        rvCarColor.setLayoutManager(layoutManager);
        rvCarColor.setAdapter(colorAdapter);

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mColorDialog.dismiss();
            }
        });
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvCarColor.setText(colorAdapter.getSelectedColor());
                mColorDialog.dismiss();
            }
        });

        mColorDialog.setContentView(dialogView);
        mColorDialog.setCancelable(true);
        mColorDialog.setCanceledOnTouchOutside(true);

        Window dialogWindow = mColorDialog.getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (mDisplay.getWidth() * 0.86);
        dialogWindow.setAttributes(p);
        mColorDialog.show();
    }
    private int getDayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, 0);
        return c.get(Calendar.DAY_OF_MONTH);
    }


    private void showVehicleTips() {
        if (guideDialog == null) {
            guideDialog = new Dialog(this, R.style.AlertDialogStyle);
            ImageView mImageView = new ImageView(this);
            mImageView.setImageResource(R.mipmap.icon_vin_guide);
            guideDialog.setContentView(mImageView);
            guideDialog.setCancelable(true);
            guideDialog.setCanceledOnTouchOutside(true);

            Window dialogWindow = guideDialog.getWindow();
            WindowManager.LayoutParams p = dialogWindow.getAttributes();
            WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            Display mDisplay = windowManager.getDefaultDisplay();
            p.width = (int) (mDisplay.getWidth() * 0.86);
            dialogWindow.setAttributes(p);
        }
        guideDialog.show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == Constants.ACTIVITY_RESULT_CODE_RESET_BRAND) {
            if (data.getExtras() != null) {
                mCarBrandModel = (CarBrandModel) data.getExtras().getSerializable(Constants.TRANSMISSION_CONTENT_KEY);
                x.image().bind(ivBrandLogo, mCarBrandModel.getImageSrc(), new Callback.CommonCallback<Drawable>() {
                    @Override
                    public void onSuccess(Drawable result) {
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        ivBrandLogo.setImageResource(R.mipmap.default_icon);
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
                tvCarBrand.setText(mCarBrandModel.getChName());
                mCarInfo.setCarBrandId(mCarBrandModel.getCarBrandId());
            }
        }

    }
}
